<template>
  <!-- 发票信息table组件 -->
  <div>
    <transition name="el-zoom-in-top">
      <div
        class="download"
        v-show="checkboxSelect > 0"
        style="margin-top: 12px"
      >
        <i class="el-icon-info"></i>
        共{{ total }}项，已选择<b>{{ checkboxSelect }}</b
        >项
        <span @click="invoiceDownload">下载</span>
        <em @click="s">清空</em>
      </div>
    </transition>
    <div v-if="invoiceType == 1">
      <el-table
        ref="multipleTable"
        @selectionChange="downloadWhether"
        :data="tableData"
        stripe
        style="width: 100%"
        :row-key="getRowKeys"
        @sort-change="sortChange"
      >
        <template v-if="indivdualId != undefined || serviceId != undefined || platformId != undefined || bussinessId != undefined">
          <el-table-column width="45"></el-table-column>
        </template>
        <template v-else>
          <el-table-column type="selection" :reserve-selection="true" width="45"> </el-table-column>
        </template>
        <!-- <el-table-column prop="billNo" label="发票编码" width="140">
        </el-table-column>
        <el-table-column prop="billCode" label="发票代码"> </el-table-column> -->
        <el-table-column prop="billType" sortable="custom" label="发票类型">
          <template #default="item">
            {{ invoiceTypeObj[item.row.billType] }}
          </template>
        </el-table-column>
        <el-table-column prop="billAmount" sortable="custom" label="发票金额">
          <template #default="item">
            {{ formatNumber(item.row.billAmount) }}
          </template>
        </el-table-column>
        <el-table-column prop="billTax" sortable="custom" label="税额">
          <template #default="item">
            {{ formatNumber(item.row.billTax) }}
          </template>
        </el-table-column>
        <el-table-column prop="billedBody" sortable="custom" label="开票主体"> </el-table-column>
        <el-table-column prop="billTime" sortable="custom" label="开票日期">
          <template #default="item">
            <template v-if="item.row.billTime != null">
            {{ format("yyyy-MM-dd hh:mm:ss", new Date(item.row.billTime)) }}
            </template>
            <template v-else>
            --
            </template>
          </template>
        </el-table-column>
        <el-table-column
          prop="caozuo"
          label="操作"
          width="70"
          class-name="editor"
        >
          <template #default="item">
            <router-link
              :to="{
                path: '/invoiceDel',
                query: {
                  billType: 1,
                  id: item.row.id,
                  businessId: item.row.businessId,
									billUrl: item.row.billUrl
                },
              }"
            >
              <el-button type="text">详情</el-button>
            </router-link>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-if="tableData.length > 0"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="arrPage"
        :page-size="selectPage"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    <div class="hhh" v-if="invoiceType == 2">
      <el-table
        ref="multipleTable"
        @selectionChange="downloadWhether"
        :data="tableData"
        stripe
        style="width: 100%"
        :row-key="getRowKeys"
        @sort-change="sortChange"
      >
        <el-table-column type="selection" :reserve-selection="true" width="45"> </el-table-column>
        <el-table-column prop="billedBody" sortable="custom" label="开票主体"> </el-table-column>
        <el-table-column prop="billType" sortable="custom" label="发票类型">
          <template #default="item">
            {{ invoiceTypeObj[item.row.billType] }}
          </template>
        </el-table-column>
        <el-table-column prop="billAmount" sortable="custom" label="发票金额">
        </el-table-column>
        <el-table-column prop="taskNumber" label="关联任务数量">
          <template #default="item">
              <el-button type="text" @click="getVocationalWorkShows(item.row.businessId,item.row.billNo)">{{ item.row.taskNumber }}</el-button>
            </template>
        </el-table-column>
        <el-table-column prop="createTime" sortable="custom" label="创建时间">
          <template #default="item">
            {{ format("yyyy-MM-dd hh:mm:ss", new Date(item.row.createTime)) }}
          </template>
        </el-table-column>
        <el-table-column prop="isUploadBill" label="是否上传发票" width="140">
            <template #default="item">
              {{ isUploadBillObj[item.row.isUploadBill] }}
            </template>
        </el-table-column>
        <el-table-column
          prop="caozuo"
          label="操作"
          width="180"
          class-name="editor"
        >
          <!-- <el-upload
						class="upload-demo"
						action="https://jsonplaceholder.typicode.com/posts/"
						:on-change="handleChange"
						:file-list="fileList"
						list-type="picture">
						上传发票
					</el-upload> -->
          <template #default="item">
            <el-upload
              v-if="item.row.isUploadBill == 0"
              class="upload-demo"
              action="api"
              :show-file-list="false"
							:http-request="file => handleChange(file, item.row.id)"
            >
              上传发票
            </el-upload>
            <el-button v-if="item.row.isUploadBill == 1" type="text" @click="GeneralInvoice(item.row.businessId,item.row.billNo)"
              >作废
            </el-button>
            <!-- <a v-if="item.row.isUploadBill == 0" :href="SbillUrl" target="_blank">查看</a> -->
            <el-button v-if="item.row.isUploadBill == 1" @click="openUrl(item.row.billUrl)" type="text">查看</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-if="tableData.length > 0"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="arrPage"
        :page-size="selectPage"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
      <!-- 关联业务 -->
      <el-dialog
        title="关联业务"
        custom-class="examine-style"
        v-model="vocationalWorkShows"
        width="60%"
      >
        <div class="cardTits">
          <el-table :data="InvoiceTaskList" ref="multipleTable" @selectionChange="modifyTask" stripe style="width: 100%" @sort-change="sortChange1">
            <el-table-column prop="name" sortable="custom" label="任务名称">
            </el-table-column>
            <el-table-column prop="businessName" sortable="custom" label="发布企业">
            </el-table-column>
            <el-table-column prop="platformName" sortable="custom" label="用工平台">
            </el-table-column>
            <el-table-column prop="realPayment" sortable="custom" label="实际服务款">
            </el-table-column>
          </el-table>
          <el-pagination
            v-if="tableData1.length > 0"
            @size-change="handleSizeChangeCo"
            @current-change="handleCurrentChangeCo"
            :current-page="currentPage1"
            :page-sizes="arrPage1"
            :page-size="selectPage1"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total1"
          >
          </el-pagination>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="vocationalWorkShows = false">取 消</el-button>
            <el-button @click="vocationalWorkShows = false" type="primary"
              >确 定</el-button
            >
          </span>
        </template>
      </el-dialog>
      <!-- 上传发票 -->
      <el-dialog
        title="上传进度"
        custom-class="examine-style"
        v-model="uploadShow"
        width="50%"
				@before-close="uploadClose"
      >
        <div class="cardTits">
          <el-row>
            <el-col :span="6">
              <div class="table-title">文件名称</div>
            </el-col>
            <el-col :span="6">
              <div class="table-title">大小</div>
            </el-col>
            <el-col :span="6">
              <div class="table-title">进度</div>
            </el-col>
            <el-col :span="6">
              <div class="table-title">操作</div>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <div class="table-content">{{ fileList[fileid].name }}</div>
            </el-col>
            <el-col :span="6">
              <div class="table-content">
                {{ fileList[fileid].size / 1000 + "KB" }}
              </div>
            </el-col>
            <el-col :span="6">
              <div class="table-content" style="width: 80%">
                <el-progress
                  :text-inside="true"
                  :stroke-width="20"
                  :percentage="percent"
                ></el-progress>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="table-content" style="margin-top: 0">
                <el-upload
                  class="upload-demo"
                  action="api/oss/invoice"
									:show-file-list="false"
                  :http-request="file => handleChange(file, fileid)"
                >
                  重新上传
                </el-upload>
                <el-button
                  style="
                    margin-left: 10px;
                    font-weight: normal;
                    font-size: 12px;
                    position: relative;
                    top: -2px;
                  "
                  type="text"
                  >取消</el-button
                >
              </div>
            </el-col>
          </el-row>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import axios from "axios";
export default {
  props: ["invoiceType", "search", "serviceId", "bussinessId", "indivdualId", 'platformId'],
  data() {
    return {
      getRowKeys(row) {
        // 获取row的key值
        return row.id;
      },
      orderByZH: false,
      orderByAsc: false,
      orderByColume: 'createTime',
      fileList: {},
      fileid: null,
      vocationalWorkShows: false,
      uploadShow: false,
      checkboxSelect: 0,
      tableData2: [
        {
          files: "小红帽普通发票",
          size: "100k",
        },
      ],
      tableData: [],
      InvoiceTaskList: [],
      currentPage: 1,
      taskIds: [],
      total: 0, // 总条数
      arrPage: [10, 20], // 每页条数
      selectPage: 10, // 每页选中条数
      tableData1: [], // 关联业务
      currentPage1: 1,
      total1: 0, // 总条数
      arrPage1: [10, 20], // 每页条数
      selectPage1: 10, // 每页选中条数
      billdwonload: [],
      modifyTasks: [],
      invoiceTypeObj: {
        1: "专项增值税发票",
        2: "普通增值税发票",
      },
      isUploadBillObj: {
        0: "否",
        1: "是",
      },
      
			percent: 0
    };
  },
  mounted() {
    this.getTableAll()
  },
  watch: {
    fileid(val) {
      if (val == null) {
        this.uploadShow = false;
      } else {
        this.uploadShow = true;
      }
    },
  },
  methods: {
		getTableAll() {
			if (this.serviceId) {
				// 服务者
				this.getServiceTableData();
			} else if (this.bussinessId) {
				// 企业
				this.getBussinessTableData();
			} else if (this.indivdualId) {
				// 个体户
				this.getIndivdualTableData();
			} else if (this.platformId) {
				//灵工平台
				this.getPlatformTableData();
			} else {
				this.getTableData();
			}
		},
    GeneralInvoice(id,billNo){
      // 发票作废
      this.$http({
        url: "/api/invoice/cancelGeneralInvoice",
        method: "post",
        headers: {
          "Content-Type": "application/json",
        },
        data: {
          selfBusinessId: id, 
          generalInvoiceNo: billNo, 
        },
      }).then((data) => {
        if (data.code === 0) {
          this.$message.success("作废成功")
          this.getTableData()
        }
      });
    },
    getTableData() {
      // 获取列表信息
      this.$http({
        url: "/api/invoice/selectInvoiceListByParam",
        method: "post",
        headers: {
          "Content-Type": "application/json",
        },
        data: {
          billType: this.invoiceType, // 发票类型
          isUploadBill: this.isUploadBill, // 发票类型
          platformId: "", // 灵活用工平台id
          invoiceId: "", // 发票id
          mixedStr: this.search,
          pageNum: this.currentPage,
          pageSize: this.selectPage,
          orderByAsc: this.orderByAsc, // 是否正序
          orderByColume: this.orderByColume, // 排序字段
          orderByZH: this.orderByZH, // 是否汉字
        },
      }).then((data) => {
        if (data.code === 0) {
          this.tableData = data.result.list;
          this.total = data.result.total;
        }
      });
    },
    getServiceTableData() {
      // 获取服务者发票列表信息
      this.$http({
        url: "/api/sevicer/selectInvoiceInfoBySevicerId",
        method: "post",
        headers: {
          "Content-Type": "application/json",
        },
        data: {
          mixedStr: "",
          pageNum: this.currentPage,
          pageSize: this.selectPage,
          platformId: "",
          sevicerId: this.serviceId,
          orderByAsc: this.orderByAsc, // 是否正序
          orderByColume: this.orderByColume, // 排序字段
          orderByZH: this.orderByZH, // 是否汉字
        },
      }).then((data) => {
        if (data.code === 0) {
          this.tableData = data.result.list;
          this.total = data.result.total;
        }
      });
    },
    getIndivdualTableData() {
      // 获取个体户发票列表信息
      this.$http({
        url: "/api/selfbusiness/selectInvoiceInfoBySelfId",
        method: "post",
        headers: {
          "Content-Type": "application/json",
        },
        data: {
          selfBusinessId: this.indivdualId, // 个体户id
          pageNum: this.currentPage,
          pageSize: this.selectPage,
          orderByAsc: this.orderByAsc, // 是否正序
          orderByColume: this.orderByColume, // 排序字段
          orderByZH: this.orderByZH, // 是否汉字
        },
      }).then((data) => {
        if (data.code === 0) {
          this.tableData = data.result.list;
          this.total = data.result.total;
        }
      });
    },
    getTableDataCo(id) {
      // 获取关联任务列表
      this.$http({
        url: "/api/invoice/selectInvoiceTaskList",
        method: "post",
        headers: {
          "Content-Type": "application/json",
        },
        data: {
          billType: this.invoiceType, // 发票类型
          platformId: "", // 灵活用工平台id
          invoiceId: id, // 发票id
          mixedStr: "",
          pageNum: this.currentPage1,
          pageSize: this.selectPage1,
        },
      }).then((data) => {
        if (data.code === 0) {
          // 筛选需要选中的数据
          let arrSelect = []
          for(let i = 0; i < data.result.list.length; i++) {
            if(data.result.list[i].invoiceId == id) {
              arrSelect.push(data.result.list[i])
            }
          }
          this.tableData1 = data.result.list;
          this.total1 = data.result.total;
          setTimeout(() => {
            this.toggleSelection(arrSelect)
          }, 10)
        }
      });
    },
    getBussinessTableData() {
      // 企业开票
      this.$http({
        url: "/api/business/selectInvoiceInfoByBusinessId",
        method: "post",
        headers: {
          "Content-Type": "application/json",
        },
        data: {
          businessId: this.bussinessId, // 企业id
          mixedStr: "",
          pageNum: this.currentPage,
          pageSize: this.selectPage,
        },
      }).then((data) => {
        if (data.code === 0) {
          this.tableData = data.result.list;
          this.total = data.result.total;
        }
      });
    },
		getPlatformTableData() {
      // 获取灵工平台发票列表信息
      this.$http({
        url: "/api/platform/selectInvoiceInfoByPlatformId",
        method: "post",
        headers: {
          "Content-Type": "application/json",
        },
        data: {
					billType: 0,
					mixedStr: "",
					invoiceId: '',
          pageNum: this.currentPage,
          pageSize: this.selectPage,
          platformId: this.platformId
        },
      }).then((data) => {
        if (data.code === 0) {
          this.tableData = data.result.list;
          this.total = data.result.total;
        }
      });
    },
    handleChange(param, id) {
      // 上传
      this.fileList[id] = param.file;
      this.fileid = id;
			const form = new FormData()
      // 文件对象
      form.append('img', param.file)
			let _this = this
			_this.percent = 0
			axios({
        method: "POST",
        url: "/api/oss/invoice?id="+ id +"&Name=" + param.file.name,
				headers: {
          "content-type": "multipart/form-data",
          "Authorization": localStorage.getItem("hegui_token")
        },
				onUploadProgress(event) {
					// 设置上传进度
					_this.percent = event.loaded/event.total*100
				},
        data: form
      }).then((res) => {
        console.log(res)
        this.uploadShow = false;
        this.$message.success("上传成功");
        this.getTableData();
      })
        .catch((err) => {
          console.log(err);
        });
    },
		uploadClose() {
			// 关闭上传弹出
			if (this.serviceId) {
				// 服务者
				this.getServiceTableData();
			} else if (this.bussinessId) {
				// 企业
				this.getBussinessTableData();
			} else if (this.indivdualId) {
				// 个体户
				this.getIndivdualTableData();
			} else {
				this.getTableData();
			}
		},
    handleSizeChange(val) {
      // 切换每页条数调用
      this.selectPage = val;
      this.getTableAll();
    },
    handleCurrentChange(val) {
      // 切换当前页数调用
      this.currentPage = val;
      this.getTableAll();
    },
    handleSizeChangeCo(val) {
      // 切换每页条数调用
      this.selectPage1 = val;
      this.getTableData();
    },
    handleCurrentChangeCo(val) {
      // 切换当前页数调用
      this.currentPage1 = val;
      this.getTableData();
    },
    handleSelectionChange() {},
    downloadWhether(d) {
      this.checkboxSelect = d.length;
      this.billdwonload = d;
    },
    // 修改关联业务
    modifyTask(d) {
      this.modifyTasks = []
      for(let i = 0; i<d.length; i++) {
        this.modifyTasks.push(d[i].taskId)
      }
    },
    openUrl(url) {
      // 打开新窗口查看协议
      let newwin = window.open()
      // window.open(url)
      newwin.document.write("<img src="+ url +" />")
		},
    getVocationalWorkShows(id,billNo){
      this.vocationalWorkShows = true
      // 查看关联业务
      this.$http({
        url: "/api/invoice/selectGeneralInvoiceTaskList",
        method: "post",
        headers: {
          "Content-Type": "application/json",
        },
        data: {
          businessId: id,
          invoiceNo: billNo,
          pageNum: this.currentPage,
          pageSize: this.selectPage,
          orderByAsc: this.orderByAsc, // 是否正序
          orderByColume: this.orderByColume, // 排序字段
          orderByZH: this.orderByZH, // 是否汉字
        },
      }).then((data) => {
        if (data.code === 0) {
          this.InvoiceTaskList = data.result.list;
        }
      });
      
    },
    sortChange(d) {
				// 监听排序
      if(d.prop == null) {
        // 默认排序方式
        this.orderByZH = false
        this.orderByAsc = false
        this.orderByColume = 'createTime'
      }else {
        let orderByZH = false
        if(d.prop == "businessName" || d.prop == "industyMsg" || d.prop == "platformName" || d.prop == "name") {
          orderByZH = true
        }
        this.currentPage = 1
        this.selectPage = 10
        let orderByAsc = d.order == "descending" ? false : true
        this.orderByZH = orderByZH
        this.orderByAsc = orderByAsc
        this.orderByColume = d.prop
      }
      if (this.serviceId) {
				// 服务者
				this.getServiceTableData();
			} else if (this.bussinessId) {
				// 企业
				this.getBussinessTableData();
			} else if (this.indivdualId) {
				// 个体户
				this.getIndivdualTableData();
			} else if (this.platformId) {
				//灵工平台
				this.getPlatformTableData();
			} else {
				this.getTableData();
			}
    },
    sortChange1(d) {
        // 监听排序
        if(d.prop == null) {
            // 默认排序方式
            this.orderByZH = false
            this.orderByAsc = false
            this.orderByColume = 'createTime'
        }else {
            let orderByZH = false
            if(d.prop == "businessName" || d.prop == "industyMsg" || d.prop == "platformName" || d.prop == "name") {
            orderByZH = true
            }
            this.currentPage = 1
            this.selectPage = 10
            let orderByAsc = d.order == "descending" ? false : true
            this.orderByZH = orderByZH
            this.orderByAsc = orderByAsc
            this.orderByColume = d.prop
        }
        this.getVocationalWorkShows();
    },
    cleanSelection() {
      // 清空选择
      this.$refs.multipleTable.clearSelection();
    },
    vocationalWork(id) {
      // 关联业务
      this.vocationalWorkShows = true;
      this.getTableDataCo(id);
    },
    upload() {
      // 上传发票
      this.uploadShow = true;
    },
    uploadCal() {
      // 上传发票
      this.uploadShow = false;
    },
    invoiceDownload() {
      // 发票下载
      let billNo = new FormData();
      for (let i = 0; i < this.billdwonload.length; i++) {
        billNo.append("list", this.billdwonload[i].billNo);
      }
      billNo.append("billType", this.invoiceType)
      axios({
        method: "POST",
        url: "/api/invoice/invoiceExcel",
        data: billNo,
        responseType: "blob",
        headers: {
          Authorization: localStorage.getItem("hegui_token")
        }
      })
        .then((res) => {
          const blob = new Blob([res.data]);
          const downloadElement = document.createElement("a");
          const href = window.URL.createObjectURL(blob);
          //后台再header中传文件名
          downloadElement.href = href;
          downloadElement.download = "发票信息"+ this.format("yyyyMMddhhmmss", new Date()) +".zip";
          document.body.appendChild(downloadElement);
          downloadElement.click();
          document.body.removeChild(downloadElement); // 下载完成移除元素
          window.URL.revokeObjectURL(href); // 释放掉blob对象
        })
        .catch((err) => {
          console.log(err);
        });
    },
    toggleSelection(rows) {
      // 手动勾选关联任务
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    }
  },
};
</script>
<style scoped>
.table-content {
  margin-top: 10px;
}
</style>
<style>
.upload-demo .el-upload--text {
  width: auto;
  border: 0;
  height: 35px;
  float: left;
  background: none;
  font-size: 12px;
  position: relative;
  top: 9px;
  color: #409eff;
}
.addBusiness {
  position: absolute;
  right: 85px;
  top: 40px;
  color: #fff;
  background: #326cf0;
  padding: 10px 30px;
  font-size: 12px;
  border-radius: 5px;
  cursor: pointer;
  z-index: 111;
}
</style>
